package 系统复习.回溯算法;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashSet;
import java.util.List;

/**
 * 给定一个可包含重复数字的序列 nums ，按任意顺序 返回所有不重复的全排列。
 */
public class L47 {

    List<List<Integer>> result = new ArrayList<>();
    List<Integer> page = new ArrayList<>();

    public List<List<Integer>> permuteUnique(int[] nums) {
        int[] numArr = new int[nums.length];
        Arrays.sort(nums);
        backtracking(nums, numArr);
        return result;
    }

    private void backtracking(int[] nums, int[] numArr) {
        if (page.size() == nums.length) {
            result.add(new ArrayList<>(page));
            return;
        }

        for (int i = 0; i < nums.length; i++) {
            if (numArr[i] != 0) continue;
            if (i > 0  && numArr[i-1] != 0 && nums[i] == nums[i-1]) continue;
            numArr[i] = 1;
            page.add(nums[i]);
            backtracking(nums, numArr);
            page.remove(page.size() - 1);
            numArr[i] = 0;
        }
    }


    public static void main(String[] args) {
        L47 l47 = new L47();
        List<List<Integer>> lists = l47.permuteUnique(new int[]{3,3,0,3});
        lists.forEach(list -> {
            list.forEach(s -> System.out.print(s + " "));
            System.out.println();
        });

    }

}
